package com.lm.redisson.controller;

import jakarta.annotation.Resource;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/limit")
public class LimitController {

    @Resource
    private RedissonClient redissonClient;

    @GetMapping("/semaphore")
    public String semaphore() throws InterruptedException {
        RSemaphore semaphore = redissonClient.getSemaphore("limit-semaphore");

        // 初始化为 3（仅限 3 个请求同时执行）
        semaphore.trySetPermits(3);

        if (semaphore.tryAcquire()) {
            try {
                Thread.sleep(2000);
                return "任务执行成功";
            } finally {
                semaphore.release();
            }
        }
        return "限流中，请稍后再试";
    }
}
